//
//  Action.m
//  ___PROJECTNAME___
//
//  Created by Goffredo Marocchi on 8/14/10.
//  Copyright 2010 unofficial_sio2_template. All rights reserved.
//

#import "Action.h"

@interface Action ()

@property (assign) float globalClock;
@property (assign) float timeStart;
@property (assign) float stepTime;
@property (assign) int stepsProcessed;

-(void) resetDeltaTime;

@end

@implementation Action

@synthesize actionDuration, timeStart, globalClock, steps, stepTime, stepsProcessed, deltaTime, repeats;

//TODO: there should be a way to register a callback.

+(id) ActionWithDuration:(float)time withDeltaTime:(float)dtime withStepsCount:(int)n isRepeating:(BOOL)r{
	Action* act = [[Action alloc] init];
	[act autorelease];
	
	[act setActionDuration:time];
	[act setTimeStart:0];
	[act setGlobalClock:0];
	[act setSteps:n];
	[act setStepTime:(time/n)];
	[act setStepsProcessed:0];
	[act setRepeats:r];
	
	return act;
}

-(BOOL) processAction  {
	timeStart += deltaTime;
	
	if ( (stepsProcessed == steps) && repeats) {
		stepsProcessed = 0;
	}
	
	if ( (timeStart >= stepTime) && (stepsProcessed < steps) ){
		
		float temp = timeStart / stepTime;
		BOOL shouldDoubleStep = (temp >0.5f); //this should help the system not to miss an action's step.
		timeStart = 0;
		if (shouldDoubleStep) stepsProcessed +=2;
		else stepsProcessed++;
		
		return YES;
	}
	
	return NO;
}

-(void) resetDeltaTime {
	timeStart = 0;
	globalClock = 0;
	stepsProcessed = 0;
}

-(void) dealloc {
	[super dealloc];
}

@end
